#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>
#include <QMessageBox>
#include <QFile>
#include <QProcess>
#include "threadshell.h"
#include "clientsocket.h"
#include "QTimer"

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    //Th_SendGps = new ThSendGps();//初始化线程
    //timer = new QTimer(this);
    sh =new ThreadShell;
    pingsh =new ThreadShell;
    shnet =new ThreadShell;
    client= new ClientSocket();
    setupUi(this);
    serialPort=new ManageSerialPort;
  //  connect(timer,SIGNAL(timeout()),this,SLOT(timerUpDate()));
    connect(bt_gps_start,SIGNAL(clicked()), this, SLOT(testgps()));//打开gps连接
    connect(bt_gps_end, SIGNAL(clicked()), this, SLOT(stopgps()));//测试gps连接
    connect(serialPort,SIGNAL(newDataReceived(QByteArray)),this,SLOT(showdata(const QByteArray &)));//接收gps数据连接
    connect(bt_gprs_send,SIGNAL(clicked()),this,SLOT(senddate()));//发送AT连接
    connect(bt_start,SIGNAL(clicked()),this,SLOT(connectserver()));//开始连接
    connect(bt_end,SIGNAL(clicked()),this,SLOT(stopgps()));//结束连接
    connect(client,SIGNAL(error(QString)),this,SLOT(showerror(const QString)));//Client输出到屏幕的连接
    connect(client,SIGNAL(success()),this,SLOT(successTimes()));//Client输出到屏幕的连接
    connect(this,SIGNAL(error(QString)),this,SLOT(showerror(const QString)));//widget类输出到屏幕的连接


    textEdit_show->setReadOnly(true);
    if(initFileInfo() == 0)//如何读取文件失败 程序退出
        exit(0);
    a=0;//获取经纬度的标记
    alltimes =0;    //当局部变量
    receive_flag=0; //接收标记
    gprsflg=0;      //让gprs发送标志为0
    AllSendTimes=0;//统计发送次数 ，初始化为0
    SuccessTimes=0;//统计成功发送次数，初始化为0
    sendflg=0;
  //  timer->start(20000);
}

Widget::~Widget()
{

    delete pingsh;
    delete client;
    delete sh;
    delete serialPort;

}

void Widget::showerror(const QString error)
{
     // QMessageBox::information( this, "Application name",error,"OK" );
        textEdit_show->insertPlainText(error);
}

void Widget::OpenPort(QString devname,int btlv)
{
    BaudRateType Btr;
    //serialPort->setPort(QLatin1String("/dev/ttyS0"));
    serialPort->setPort("/dev/"+devname);
    if(btlv == 9600)
    {
        Btr=BAUD9600;
    }
    else if(btlv == 115200)
    {
        Btr = BAUD115200;
    }
    else
    {
        QMessageBox::warning(0,tr("config "),tr("Lack of parameters ,Please Check config file！"));
        exit(0);
    }
    serialPort->setBaudRate(Btr);
    serialPort->setDataBits(DATA_8);
    serialPort->setParity(PAR_NONE);
    serialPort->setStopBits(STOP_1);
    serialPort->setFlowControl(FLOW_OFF);
    serialPort->setTimeout(0,10);
    serialPort->enableSending();
    serialPort->enableReceiving();
    if( serialPort->isOpen() )
    {
        serialPort->close();
    }
    if( serialPort->open() )
    {
        serialPort->receiveData();
        label_3->setText("success open "+GpsDev);
    }
    else
    {
         label_3->setText("failed open "+GpsDev);
    }

}

void Widget::showdata(const QByteArray &dataReceived)
{

       if(gprsflg == 1)//gprs用
       {
          allDataReceived += dataReceived;
          textEdit_show->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
          QTextStream in(dataReceived);
          in.setAutoDetectUnicode(false);
          QString decodedStr = in.readAll();
          textEdit_show->insertPlainText(decodedStr);
          return ;
        }

        QRegExp rx("(.*)\\$(.*)"); //用正则表达式 找出来包含回车的字符串
        if(rx.exactMatch(dataReceived))
        {

            int pos=rx.indexIn(dataReceived);
            if( pos > -1)
            {
                 QString jingdu,weidu;
                 value1 = rx.cap(1);
                 value2 = rx.cap(2);
                 CompleteSts= allDataReceived+value1.toAscii();
                 allDataReceived="$"+value2.toAscii();
                 if(CompleteSts.mid(1,5)=="GPGGA")
                 {
                      // textEdit_show->insertPlainText(CompleteSts);
                       textEdit_show->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
                       jingdu = CompleteSts.mid(18,9);
                       weidu  = CompleteSts.mid(30,10);
                       if(sendflg != 1)
                       {
                       textEdit_show->insertPlainText("longitude is "+jingdu+"\n");
                       textEdit_show->insertPlainText("latitude  is "+weidu+"\n");
                       }

                       alltimes++;
                 }
                 if(alltimes == frequency )
                 {
                     QString stime = gettime();
                     QString Sendstr;
                     Sendstr = uname + "," + upasswd +","+ jingdu + "," + weidu + "," + stime;

                     if( sendflg == 1 )
                     {
                         AllSendTimes++;

                         error(Sendstr+"\r\n");
                         error("\r\n");
                         client->SendGps(Sendstr);
                         f_t=AllSendTimes-SuccessTimes;
                         label_3->setText("Send       "+QString::number(AllSendTimes)+"  times\r\n"+"Success "+QString::number(SuccessTimes)+ \
                                          "  times\r\n"+"Faile        "+QString::number(f_t)+"  times");
                     }
                     alltimes = 0;

                 }

            }

        }
        else
        {
           allDataReceived +=dataReceived;
        }
        if( receive_flag != 1 )
        {
           receive_flag = 1;
           label_3->setText("success receive data!!");
        }

}

void Widget::stopgps()
{
    serialPort->close();
    sendflg = 0;
    gprsflg = 0;
   // InitNet();
}

void Widget::senddate()
{



 /*   gprsflg = 1;//设置gprs标志
    textEdit_show->clear();
    OpenPort(GprsDev,GprsBotelv);
    QString  message;
    //message = lineEdit->text();
    message="AT";
    message += "\x0D\x0A";
    QByteArray temp(message.toUtf8());
    serialPort->sendData(temp);*/
}

void Widget::connectserver()
{
    client->SetIp(serverip);
    client->SetPort(serverport);
    sendflg = 1;
    gprsflg = 0;//不可用
    OpenPort(GpsDev,GpsBotelv);
}
QString Widget::gettime()//获取当前时间
{
    QDateTime time = QDateTime::currentDateTime();
    QString strtime = time.time().toString();
    int c_year = time.date().year();
    int c_mouth = time.date().month();
    int c_today = time.date().day();
    QString cdate = QString::number(c_year) + "-" + QString::number(c_mouth) + "-" + QString::number(c_today) + " " + strtime;
    //emit error(cdate);
    return cdate;
}


int Widget::initFileInfo()
{
    QString filepath=QApplication::applicationDirPath ();//获取程序当前路径
    filepath=filepath+"/config";
    QFile file(filepath);
    QString strLine;
    int i=0;
    if(file.open(QIODevice::ReadOnly))
    {
        while(!file.atEnd())
        {
        strLine=file.readLine();
        strLine=strLine.split("#").at(0);
        strLine=strLine.trimmed();
        i++;
        switch(i)
        {
        case 1:
             serverip =strLine;//服务端ip
             label_ip->setText(serverip);
             break;
        case 2:
             serverport = strLine.toInt();//端口
             label_port->setText(strLine);
             break;

        case 3:
             uname = strLine;//用户名
             label_username->setText(uname);
              break;

        case 4:
             upasswd = strLine;//密码
             label_passwd->setText(upasswd);
             break;

        case 5:
             frequency = strLine.toInt();//频率
             frequency=frequency*10;
             label_frequency->setText(strLine+" minute");
             break;
        case 6:
             phonenumber = strLine.toInt();//电话
             label_phone->setText(strLine);
             break;
        case 7:
             GpsDev = strLine;//Gps端口
             label_Gpsdev->setText(strLine);
             break;
        case 8:
             GpsBotelv = strLine.toInt();//波特率
             //label_botelv->setText(strLine);
             break;
        case 9:
             GprsDev = strLine;//Gps端口
             label_Gprsdev->setText(strLine);
             break;
        case 10:
             GprsBotelv = strLine.toInt();//波特率
             //label_botelv->setText(strLine);
             break;
        }
        }
    }
    else
    {
        QMessageBox::warning(0,tr("Open Error!"),tr("Please Check config file！"));
        return 0;
    }
    if(label_Gprsdev->text() == "0")
    {
        QMessageBox::warning(0,tr("config "),tr("Lack of parameters ,Please Check config file！"));
        return 0;
    }
    file.close();
    return 1;

}

int Widget::writefile(QString text, int pos)
{
    text="1";
    pos = 1;
    /*QString filepath = QApplication::applicationDirPath ();//获取程序当前路径
    filepath = filepath + "/config";
    QFile file(filepath);
    QString str;
    QStringList strlist;
    str = readfile();
    strlist = str.split(";");
    str.clear();
    for(int i=0;i<strlist.size();i++)
    {
        if(i != pos)
        {

            if(i == strlist.size()-1)
            {
                str = str + strlist.at(i);
            }
            else
            {
                str = str+strlist.at(i)+";";
            }
        }
        else
        {
            if(i == strlist.size()-1)//防止一直加分号
            {
                str = str+text;
            }
            else
            {
                str = str +text +";";
            }

        }
    }

    if(file.open(QIODevice::WriteOnly))
    {

        QTextStream out(&file);
        out<<str;
        file.close();
        return 1;
    }*/
    return 0;
}

void Widget::testgps()
{
    textEdit_show->clear();
    sendflg = 0;
    OpenPort(GpsDev,GpsBotelv);
}

//初始化网络
/*网络模块说明，使用pppd call somescript 方式连接外网 会遇到两个问题，1，连接失败，这个情况容易解决
  参考http://blogold.chinaunix.net/u3/93670/showart_2263527.html
在配置参数中加上persist  在保证进程不退出时 会自动去连 问题2，由连上去后 如果36秒无数据发送，会自动断开，这时
我采取到方案是，设置一个定时器，每20秒 ping一下服务器,理论上可以36秒ping1次 最省流量，但由于36不可保证，所以
设为20秒，如果gprs连上网络了，就会一直保持网络畅通，在ping之前 加上判断，看进程中是否存在拨号协议进程，如果不存在，就启动一个，这样就可以保证网络
畅通*/
int Widget::InitNet()
{

   // OpenPPP();
    timerUpDate();
    return 0;
}

void Widget::successTimes()
{
    SuccessTimes++;
    f_t=AllSendTimes-SuccessTimes;
    label_3->setText("Send  "+QString::number(AllSendTimes)+"  times\r\n"+"Success "+ \
                     QString::number(SuccessTimes)+"times\r\n"+" Faile "+QString::number(f_t)+"times");

}
void Widget::timerUpDate()
{
    QProcess *cmd =new QProcess(this);
    cmd->execute("ping  61.135.169.125");
    QString str=cmd->readAll();
    error(str);

  //  pingsh->rec_shell("ping -c 1 61.135.169.125");
  //  pingsh->setflg(2);//
  //  pingsh->start();

}

void Widget::TestNet()
{
    shnet->setflg(1);
    shnet->rec_shell("");
}

void Widget::OpenPPP()
{
    sh->rec_shell("bash /home/xienan/initnet");
    sh->setflg(1);//执行一次
    sh->start();
}
